const nodemailer = require('nodemailer')

// 当前采用 163 邮箱，如需其他邮箱需要去配置
const transporter = nodemailer.createTransport({
    // service: 'Gmail',
    // auth: {
    //     user: process.env.EMAIL_USER,
    //     pass: process.env.EMAIL_PASS,
    // },
    host: 'smtp.163.com',
    port: 465,
    secure: true,
    auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS,
    },
})

// 发送验证码到邮箱
async function sendVerificationEmail(email, code, type = 'reset_password') {
    const subjectMap = {
        register: '注册验证码',
        login: '登录验证码',
        reset_password: '密码重置验证码'
    }

    const mailOptions = {
        from: `"系统通知" <${process.env.EMAIL_USER}>`,
        to: email,
        subject: subjectMap[type] || '验证码',
        html: `
            <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
                <h2>验证码通知</h2>
                <p>您的验证码是：</p>
                <div style="font-size: 32px; font-weight: bold; color: #1890ff; letter-spacing: 8px; margin: 20px 0;">
                    ${code}
                </div>
                <p>验证码有效期：<strong>5分钟</strong></p>
                <p style="color: #999; font-size: 12px;">如非本人操作，请忽略此邮件。</p>
            </div>
        `
    }

    try {
        await transporter.sendMail(mailOptions)
        return true
    } catch (error) {
        console.error('邮件发送失败:', error)
        return false
    }
}

module.exports = { sendVerificationEmail }